package com.itwmk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itwmk.entity.*;
import com.itwmk.service.impl.CategoryService;
import com.itwmk.service.impl.DishFavorService;
import com.itwmk.service.impl.DishService;
import com.itwmk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author wmk
 */
@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFavorService dishFavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dto
     * @return
     */
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dto){
        dishService.myAddDish(dto);
        //全局清理
//        Set<Object> keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //部分清理
        String key="dish_"+dto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增成功");
    }

    /**
     * 分页查询菜品信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page> queryDish(int page,int pageSize,String name){
        //需要通过dtoPage对categoryName进行补充
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>(page, pageSize);
        //在Dish表中查出所有菜品信息（name为条件）
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name),Dish::getName,name);
        wrapper.orderByAsc(Dish::getName);
        dishService.page(dishPage,wrapper);

        //将dishPage内容拷贝到dtoPage中，其中records属性不拷贝
        BeanUtils.copyProperties(dishPage,dtoPage,"records");

        //遍历disPage中的records，通过categoryId查到对应CategoryName
        //将CategoryName补充到dtoPage中的records中
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dtoRecords=new ArrayList<>();
        for (Dish d:records) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(d,dto);
            Category category = categoryService.getById(d.getCategoryId());
            String categoryName = category.getName();
            dto.setCategoryName(categoryName);
            dtoRecords.add(dto);
        }
        dtoPage.setRecords(dtoRecords);
        return R.success(dtoPage);
    }

    @GetMapping("{id}")
    public R<DishDto> getDishInfo(@PathVariable Long id){
        DishDto dto = dishService.getByIdWithFlavor(id);
        return R.success(dto);
    }

    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dto){
        dishService.updateWithFlavor(dto);
        String key="dish_"+dto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

//    /**
//     * 根据categoryID查询菜品信息
//     * @param dish
//     * @return
//     */
//    @GetMapping("list")
//    public R<List<Dish>> queryDish(Dish dish){
//        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Dish::getCategoryId,dish.getCategoryId());
//        //显示启用的
//        wrapper.eq(Dish::getStatus,1);
//        wrapper.orderByAsc(Dish::getName);
//
//        List<Dish> dishList = dishService.list(wrapper);
//        return R.success(dishList);
//
//    }

    /**
     * 根据categoryID查询菜品信息
     * @param dish
     * @return
     */
    @GetMapping("list")
    public R<List<DishDto>> queryDish(Dish dish){
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        List<DishDto> dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dtoList!=null){
            return R.success(dtoList);
        }

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //显示启用的
        wrapper.eq(Dish::getStatus,1);
        wrapper.orderByAsc(Dish::getName);

        List<Dish> dishList = dishService.list(wrapper);

        dtoList=new ArrayList<>();

        for (Dish d:dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(d,dishDto);
            LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
            flavorWrapper.eq(DishFlavor::getDishId,d.getId());
            List<DishFlavor> flavorList = dishFavorService.list(flavorWrapper);
            dishDto.setFlavors(flavorList);
            dtoList.add(dishDto);
        }
        //查询并缓存
        redisTemplate.opsForValue().set(key,dtoList,2, TimeUnit.HOURS);
        return R.success(dtoList);
    }

}
